package com.gzhryc.shared_device.oem.h5.agent.jetty;

import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.servlet.AllowOriginsHelper;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonFilter implements Filter {

	final static Logger log = Logger.getLogger(CommonFilter.class);

	private static Pattern _Pat1 = Pattern.compile("^/wx_event/.*$");
	private static Pattern _Pat2 = Pattern.compile("^/outside/callback/.*$");
	private static Pattern _Pat3 = Pattern.compile("^/[a-z0-9]+\\.html$");

	AllowOriginsHelper allowOriginsHelper;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		allowOriginsHelper = new AllowOriginsHelper();
		allowOriginsHelper.addAddress("all");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = HttpServletRequest.class.cast(request);
		HttpServletResponse httpResponse = HttpServletResponse.class.cast(response);

		String uri = httpRequest.getRequestURI();
		if (uri.contains("/favicon.ico")) {
			return;
		}

		// 跨域设置
		allowOriginsHelper.setAllowOrigins(httpRequest, httpResponse);

		//微信域名验证
		if (uri.endsWith(".txt")) {
			String fileName = uri.substring(uri.lastIndexOf("/") + 1);
			WebUtils.setResponseContentType(httpResponse, uri);
			String filePath = httpRequest.getServletContext().getRealPath(URLDecoder.decode(fileName, "UTF-8"));
			log.info("微信域名验证，" + filePath);
			WebUtils.readResource(httpResponse, filePath);
			return;
		}
		
		//支付宝域名验证
		Matcher mat3 = _Pat3.matcher(uri);
		if (mat3.find()) {
			String fileName = uri.substring(uri.lastIndexOf("/") + 1);
			WebUtils.setResponseContentType(httpResponse, uri);
			String filePath = httpRequest.getServletContext().getRealPath(URLDecoder.decode(fileName, "UTF-8"));
			log.info("支付宝域名验证，" + filePath);
			WebUtils.readResource(httpResponse, filePath);
			return;
		}

		//微信事件回调
		Matcher mat1 = _Pat1.matcher(uri);
		if (mat1.find()) {
			chain.doFilter(httpRequest, httpResponse);
			return;
		}

		//外部接口回调
		Matcher mat2 = _Pat2.matcher(uri);
		if (mat2.find()) {
			chain.doFilter(httpRequest, httpResponse);
			return;
		}

		String userAgent = httpRequest.getHeader("User-Agent");
		if (WebConstants.isDebug() == 0) {
			if (!WebUtils.isWxClient(httpRequest) || !WebUtils.isMobileOrTablet(httpRequest)) {
				log.error("访问阻止：{{0}}，userAgent = {{1}}", uri, userAgent);
				AjaxResult result = new AjaxResult(DtoConstants.NOT_POWER, "请使用微信手机端");
				WebUtils.toJson(httpResponse, result);
				return;
			}
		}else {
			log.info("userAgent = {{0}}，path = {{1}}", userAgent, uri);
		}

		try {
			// 处理普通静态资源
			if (uri.contains("/static/")) {
				String filePath = uri;
				Integer i = uri.indexOf("/static/");
				if (i > 0) {
					filePath = uri.substring(i);
				}
				filePath = "/h5" + filePath;
				WebUtils.setResponseContentType(httpResponse, uri);
				filePath = httpRequest.getServletContext().getRealPath(URLDecoder.decode(filePath, "UTF-8"));
				WebUtils.readResource(httpResponse, filePath);
				return;
			}
		} catch (Exception e) {
			log.error("GET请求处理静态资源错误", e);
		}

		if (uri.endsWith(".do") || uri.endsWith(".data")  || uri.endsWith(".jpeg") || uri.equals("/") || uri.equals("/index.html")) {
			chain.doFilter(httpRequest, httpResponse);
		}else{
			AjaxResult result = new AjaxResult(DtoConstants.NOT_POWER, "您好～");
			WebUtils.toJson(httpResponse, result);
		}
	}

	@Override
	public void destroy() {
	}

}
